﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

namespace CSharp
{
    public class SQLDbContext:DbContext
    {
        //将DbSet作为集合对象，DbSet装入数据库
        public DbSet<Person> Persons { get; set; }
        public DbSet<Student> Students { get; set; } 
        public DbSet<Teacher> Teachers { get; set; } 
        public DbSet<Classroom> Classrooms { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string connectionstring =
                @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=18bang;Integrated Security=True;";
            optionsBuilder
                .UseSqlServer(connectionstring)
                .UseLazyLoadingProxies()
#if DEBUG
                .EnableSensitiveDataLogging()//是否记录敏感信息的开关，仅在调试状态下使用
#endif
                .LogTo(
                (id, level) => level == Microsoft.Extensions.Logging.LogLevel.Debug,  //过滤条件
                //(id,level) => level == LogLevel.Information,
                log => Console.WriteLine(log) //如何记录log
                );
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Student>().HasBaseType((Type)null);
            modelBuilder.Entity<Teacher>().HasBaseType((Type)null);
            modelBuilder.Entity<Classroom>().HasBaseType((Type)null);


            modelBuilder.Entity<Student>()
                .HasOne<Bed>(s => s.Bed)
                .WithOne(b => b.Student)
                .HasForeignKey<Student>(s => s.BedId); //1对1
                //.OnDelete(DeleteBehavior.Cascade);//即使外键可为null，也强制删除
            //ClientSetNull = 0 客户端：EF
            //SetNull 数据库

            //modelBuilder.Entity<Student>().ToTable("Students");
            modelBuilder.Entity<Teacher>(s =>
            s.HasCheckConstraint("Salary","Salary >= 0"));

            //影子属性
            //modelBuilder.Entity<Student>(opt =>
            //{
            //    opt.Property<DateTime>("EnrollDate");
            //});
        }


        //(s =>
        //    {
        //        //s.Property(m => m.OnCall).HasColumnType("NVARCAHR(20)");
        //        s.Property(m => m.Name).HasMaxLength(128);
        //        s.ToTable("DB_Student");
        //        s.HasKey(m => new { m.Name, m.IsFemale });
        //        //s.HasIndex(m => m.Name).IsUnique();
        //        s.HasCheckConstraint("CK_Age", "Age Between 0 And 130");
        //    });

        //    modelBuilder.Entity<Major>()
        //        //.Ignore(m => m.Difficulty)
        //        ;  
        //}

    }
}
